//
// Created by lfm on 25-4-14.
//

#include "Merchandise.h"
#include <string>
#include <cstring>
#include <limits>
Merchandise::Merchandise()
{
    this->m_Namep = nullptr;
    this->m_No = 0;
    this->m_Price = 0;
}
Merchandise::~Merchandise()
{
    if (this->m_Namep != nullptr)
    {
        delete m_Namep;
        m_Namep = nullptr;
    }
}
// 输入商品信息
istream& operator>>(istream& in, Merchandise& s) {
    // 释放原有内存
    if (s.m_Namep != nullptr) {
        delete[] s.m_Namep;
        s.m_Namep = nullptr;
    }

    // 读取编号和价格
    in >> s.m_No >> s.m_Price;

    // 读取名称（支持带空格）
    in.ignore(); // 清除数字后的空格
    char temp[256];
    if(in.peek() == '\n') in.ignore(); // 额外处理可能的换行符
    in.getline(temp, sizeof(temp));

    // 分配内存
    s.m_Namep = new char[strlen(temp) + 1];
    strcpy(s.m_Namep, temp);

    return in;
}
// 输出商品信息
ostream& operator<< (ostream& out, Merchandise& s)
{
    out << "名称: " << (s.m_Namep ? s.m_Namep : "[空]")
        << " | 编号: " << s.m_No
        << " | 价格: " << s.m_Price;
    return out;
}
